//TCPTransFileTest.java
package com.ylaihui.net;

import org.junit.Test;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPTransFileTest {
    @Test
    public void serverTest() throws IOException {
        ServerSocket serverSocket = new ServerSocket(65500);

        Socket socket = serverSocket.accept();

        // 读入客户端的文件流
        InputStream inputStream = socket.getInputStream();

        //读入文件并写文件到本地的流
        FileOutputStream fileOutputStream = new FileOutputStream(new File("tcp-copy.png"));

        //读取客户端的文件，并写文件到本地
        byte[] bytes = new byte[10];
        int len = 0;
        while ((len = inputStream.read(bytes)) != -1){
            fileOutputStream.write(bytes,0,len);
        }

        fileOutputStream.close();
        inputStream.close();
        socket.close();
        serverSocket.close();
    }
    @Test
    public void clientTest() throws IOException {
        Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 65500);

        OutputStream os = socket.getOutputStream();

        // 客户端读取本地文件，并将文件写入到 socket 输出流
        FileInputStream fis = new FileInputStream(new File("tcp.png"));
        byte[] bytes = new byte[10];
        int len = 0;
        while((len = fis.read(bytes)) != -1){
            os.write(bytes,0,len);
        }

        fis.close();
        os.close();
        socket.close();
    }
}
